package com.medicine.product.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.LocationConstraint;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.github.pagehelper.PageHelper;
import com.medicine.common.base.ResponseData;
import com.medicine.product.dto.HospitalOrderListVo;
import com.medicine.product.dto.OrderDto;
import com.medicine.product.mapper.TbbalanceMapper;
import com.medicine.product.mapper.TbdoctorMapper;
import com.medicine.product.param.CategoryParam;
import com.medicine.product.service.TestService;
import com.medicine.product.utils.DateUtils;
import com.medicine.product.utils.ExByteArrayOutputStream;
import com.medicine.product.utils.ExcelExportUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author lynn
 * @version 1.0
 * @date 2021/10/23
 */
@RestController
@RequestMapping("/test")
public class TestController {


    @Autowired
    private TbdoctorMapper tbdoctorMapper;
    @Autowired
    private TbbalanceMapper tbbalanceMapper;
    @Autowired
    private TestService testService;

    @RequestMapping("/api/downlownd")
    public String getOssFile(HttpServletRequest request, HttpServletResponse response){

        // endpoint以杭州为例，其它region请按实际情况填写，1改为自己的
        String endpoint = "http://oss-cn-qingdao.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建
        String accessKeyId = "51LpLjTUl2YiN0nq";
        String accessKeySecret = "pYMRfxP1uSTlm8VzMqQrecbkGQmO4H";
        String bucketName = "childvdaifu";
        //要下载的文件名（Object Name）字符串，中间用‘,’间隔。文件名从bucket目录开始.5改为自己的
        String key = "export/20211025/Vdaifu.xls,export/20211025/bianma.xlsx";
        try {
            // 初始化
            //xxxx年xx月社区医院对账单
//            String fileName = DateUtils.getHeadMoth()+"社区医院对账单";
            String fileName = "test.zip";
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //6改为自己的名称
//            String fileName = "test.zip";
            // 创建临时文件
            File zipFile = File.createTempFile("test", ".zip");
            FileOutputStream f = new FileOutputStream(zipFile);
            /**
             * 作用是为任何OutputStream产生校验和
             * 第一个参数是制定产生校验和的输出流，第二个参数是指定Checksum的类型 （Adler32（较快）和CRC32两种）
             */
            CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
            // 用于将数据压缩成Zip文件格式
            ZipOutputStream zos = new ZipOutputStream(csum);

            String[] keylist = key.split(",");
            for (String ossfile : keylist) {
                // 获取Object，返回结果为OSSObject对象
                OSSObject ossObject = ossClient.getObject(bucketName, ossfile);
                // 读去Object内容  返回
                InputStream inputStream = ossObject.getObjectContent();
                // 对于每一个要被存放到压缩包的文件，都必须调用ZipOutputStream对象的putNextEntry()方法，确保压缩包里面文件不同名

//                zos.putNextEntry(new ZipEntry(ossfile.split("/")[2]));
                zos.putNextEntry(new ZipEntry(ossfile));
                int bytesRead = 0;
                // 向压缩文件中输出数据
                while((bytesRead=inputStream.read())!=-1){
                    zos.write(bytesRead);
                }
                inputStream.close();
                zos.closeEntry(); // 当前文件写完，定位为写入下一条项目
            }
            zos.close();
            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", "%20");    //IE下载文件名空格变+号问题
            } else {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }
            response.reset();
            response.setContentType("text/plain");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Location", fileName);
            response.setHeader("Cache-Control", "max-age=0");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            FileInputStream fis = new FileInputStream(zipFile);
            BufferedInputStream buff = new BufferedInputStream(fis);
            BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());
            byte[] car=new byte[1024];
            int l=0;
            while (l < zipFile.length()) {
                int j = buff.read(car, 0, 1024);
                l += j;
                out.write(car, 0, j);
            }
            // 关闭流
            fis.close();
            buff.close();
            out.close();

            ossClient.shutdown();
            // 删除临时文件
            zipFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/api/downlownds")
    public String getOssFiles(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //计算环比
        String orderBy = "";
        Date date = new Date();
        OrderDto orderDto =new OrderDto();
//        orderDto.setPageNum(1);
//        orderDto.setPageSize(20);
        orderDto.setStartTime(DateUtils.getStartMoth());
        orderDto.setEndTime(DateUtils.getEndMoth());
        orderDto.setOrderBy("gmv desc");
        if (orderDto.getOrderBy().contains("y2y") || orderDto.getOrderBy().contains("m2m")
                || orderDto.getOrderBy().contains("grossProfit")) {
            orderBy = orderDto.getOrderBy();
            orderDto.setOrderBy(null);
        }
        if (StringUtils.isNotEmpty(orderDto.getKey())) {
            //通过医生名称查找社区id
            List<String> hospitalIds = tbdoctorMapper.findHospitalIdByDoctorName(orderDto.getKey());
            if (hospitalIds != null && hospitalIds.size() > 0) {
                orderDto.setKey(null);
                orderDto.setHospitalIds(hospitalIds);
            }
        }

//        PageHelper.startPage(orderDto.getPageNum(), orderDto.getPageSize(), orderDto.getOrderBy());
//        List<HospitalOrderListVo> list = tbbalanceMapper.orderList(orderDto);
        List<HospitalOrderListVo> list = tbbalanceMapper.ToHospitalOrderList(orderDto);
        //计算日期范围相隔天数
        long diffTime = orderDto.getStartTime() == null || orderDto.getEndTime() == null ? 0L :
                DateUtils.diffTime(orderDto.getStartTime(), orderDto.getEndTime());
        orderDto.setDiffTime(diffTime + 1);
        orderDto.setRateType(1);
        /*List<HospitalOrderListVo> rateV2mon = tbbalanceMapper.rateToHospital(orderDto);
        orderDto.setRateType(2);
        List<HospitalOrderListVo> rate2year = tbbalanceMapper.rateToHospital(orderDto);
        //获取分成比例
        testService.countToList(list, rateV2mon, rate2year);*/

        //排序
        if (orderBy.contains("m2m")) {
            list.stream().sorted(Comparator.comparing(HospitalOrderListVo::getM2m)).collect(Collectors.toList());
        }
        if (orderBy.contains("y2y")) {
            list.stream().sorted(Comparator.comparing(HospitalOrderListVo::getY2y)).collect(Collectors.toList());
        }
        if (orderBy.contains("grossProfit")) {
            list.stream().sorted(Comparator.comparing(HospitalOrderListVo::getGrossProfit)).collect(Collectors.toList());
        }

        try{
            //xxxx年xx月社区医院对账单
//            String fileData = DateUtils.getHeadMoth()+"社区医院对账单";
//            String fileName = DateUtils.getHeadMoth()+"社区医院对账单.zip";
            String fileName = "statement.zip";

//        Map<String, List<HospitalOrderListVo>> classMap = list.stream().collect(Collectors.groupingBy(HospitalOrderListVo::getSarea));
            Map<String, List<HospitalOrderListVo>> classMap = list.stream().collect(Collectors.groupingBy(t->StringUtils.isNotEmpty(t.getSarea())?t.getSarea():"其他"));

//            List<String> areas = classMap.keySet().stream().collect(Collectors.toList());

//        List<String> areas = list.stream().map(t->t.getSarea()).collect(Collectors.toList());

//            File zipFile = File.createTempFile(DateUtils.getHeadMoth()+"社区医院对账单", ".zip");
            File zipFile = File.createTempFile("statement", ".zip");
            FileOutputStream f = new FileOutputStream(zipFile);
            /**
             * 作用是为任何OutputStream产生校验和
             * 第一个参数是制定产生校验和的输出流，第二个参数是指定Checksum的类型 （Adler32（较快）和CRC32两种）
             */
            CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
            // 用于将数据压缩成Zip文件格式
            ZipOutputStream zos = new ZipOutputStream(csum);

            for(String key:classMap.keySet() ){
                List<HospitalOrderListVo> hospitalOrderListVos = classMap.get(key);
                Map<String, List<HospitalOrderListVo>> voMap = hospitalOrderListVos.stream().collect(Collectors.groupingBy(r->StringUtils.isNotEmpty(r.getShospitalid())?r.getShospitalid():"无"));
//                List<String> shospitalid = voMap.keySet().stream().collect(Collectors.toList());
                for(String keys: voMap.keySet()){
                    List<HospitalOrderListVo> h = voMap.get(keys);
                    String fileName1 = h.get(0).getShname()+".xlsx";
                    String invoiceName = h.get(0).getInvoiceName();
                    List<Map<String,String>> maps = h.stream().map(t->t.toMap()).collect(Collectors.toList());
                    ExByteArrayOutputStream baos = ExcelExportUtil.toExcel(HospitalOrderListVo.getTagNameList(),maps,fileName,"2",fileName1,invoiceName);
                    InputStream inputStream = ExcelExportUtil.streamTran(baos);
                    String s = StringUtils.isNotEmpty(h.get(0).getSarea())?h.get(0).getSarea():"其他";
                    zos.putNextEntry(new ZipEntry(s+"/"+fileName1));
                    int bytesRead = 0;
                    // 向压缩文件中输出数据
                    while((bytesRead=inputStream.read())!=-1){
                        zos.write(bytesRead);
                    }
                    inputStream.close();
                    zos.closeEntry(); // 当前文件写完，定位为写入下一条项目

//                String url = UploadFileUtils.uploadFile(ExcelExportUtil.streamTran(baos),fileName,"export/"+fileData+h.get(0).getSarea(),childOssBucket);
                }
            }
            zos.close();


            // endpoint以杭州为例，其它region请按实际情况填写，1改为自己的
            /*String endpoint = "http://oss-cn-qingdao.aliyuncs.com";
            // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建
            String accessKeyId = "51LpLjTUl2YiN0nq";
            String accessKeySecret = "pYMRfxP1uSTlm8VzMqQrecbkGQmO4H";
            String bucketName = "childvdaifu";


//            String url = UploadFileUtils.uploadFile(zipFile,"export/",childOssBucket,true);
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            FileInputStream inputStream = new FileInputStream(zipFile);
            fileName = "export/"+DateUtils.getHeadMothyyyyMM()+"/"+fileName;
            PutObjectResult result = ossClient.putObject(bucketName, fileName,
                    inputStream);
            String strResult = StringUtils.EMPTY;
            if (result != null) {
                strResult = "http://"+bucketName+".oss-cn-qingdao.aliyuncs.com/" +"/"+fileName;
            }*/

            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", "%20");    //IE下载文件名空格变+号问题
            } else {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }
            response.reset();
            response.setContentType("text/plain");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Location", fileName);
            response.setHeader("Cache-Control", "max-age=0");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            FileInputStream fis = new FileInputStream(zipFile);
            BufferedInputStream buff = new BufferedInputStream(fis);
            BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());
            byte[] car=new byte[1024];
            int l=0;
            while (l < zipFile.length()) {
                int j = buff.read(car, 0, 1024);
                l += j;
                out.write(car, 0, j);
            }
            // 关闭流
            fis.close();
            buff.close();
            out.close();

//        ossClient.shutdown();
            // 删除临时文件
            zipFile.delete();
//            return strResult;
        }catch (Exception e) {
            e.printStackTrace();
        }


//        String url = UploadFileUtils.uploadFile(zipFile,"export/",childOssBucket,true);

        return null;
    }


    @ApiOperation("社区对账单")
    @GetMapping(value = "/exOrderList")
    public String exOrderList() throws IOException {
        return testService.list();
    }

}
